package demo.letcode.top100;

import demo.letcode.ListNode;

/**
 * 删除链表的倒数第n个节点，并返回链表的头节点
 * 1>2>3>4>5 n=2
 * 当删除倒数第2个节点后
 * 1>2>3>5
 * @author taqo
 * @date 2021/5/8
 */
public class _删除链表的倒数第N个节点 {
    public static void main(String[] args) {
        ListNode head = new ListNode(0);
        int a[] = {1,2,3,4,5};
        ListNode temp = head;
        for (int i = 0; i < a.length; i++) {
            ListNode n = new ListNode(a[i]);
            temp.next = n;
            temp = n;
        }
        b(head,2);
    }

    private static void a(ListNode head, int n) {
        ListNode pre = head;
        int last = length(head) - n;
        for (int i = 0; i < last - 1; i++) {
            pre = pre.next;
        }
        pre.next = pre.next.next;
        head.print();
    }
    private static void b(ListNode head, int n) {
        ListNode pre = head;
        int last = length(head) - n;
        for (int i = 0; i < n; i++) {
            pre = pre.next;
        }
        pre.next = pre.next.next;
        head.print();
    }
    private static int length(ListNode head) {
        int len = 0;
        while (head != null) {
            len++;
            head = head.next;
        }
        return len;
    }
}
